package com.easemob.helpdesk.fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.easemob.helpdesk.activity.MainActivity;
import com.easemob.helpdesk.activity.UserActivity;
import com.easemob.helpdesk.activity.UserMsgListActivity;
import com.easemob.helpdesk.bean.BaseWebResult;
import com.easemob.helpdesk.bean.PageWithRes;
import com.easemob.helpdesk.bean.User;
import com.easemob.helpdesk.listener.OnDoubleClickListener;
import com.easemob.helpdesk.utils.CommonUtils;
import com.easemob.helpdesk.utils.DialogUtils;
import com.easemob.helpdesk.widget.AddrSearchView;
import com.easemob.helpdesk.widget.SwipeRefreshView;
import com.housekeeperapp.BuildConfig;
import com.housekeeperapp.R;
import com.net.ApiService;
import com.net.BaseResponse;
import com.net.HKHttpUtils;
import com.net.HKResponseResultCallBack;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;


import retrofit2.Call;
//import okhttp3.Call;
//import okhttp3.Callback;
//import okhttp3.FormBody;
//import okhttp3.OkHttpClient;
//import okhttp3.Request;
//import okhttp3.RequestBody;
//import okhttp3.Response;

/**
 * Created by liyuzhao on 05/04/2017.
 */

public class OwnerMsgFragment extends Fragment implements AddrSearchView.searchListener {
    private static final String TAG = OwnerFragment.class.getSimpleName();

    private InputMethodManager inputMethodManager;
    private  void initFindView(View view){
        mListView=view.findViewById(R.id.owner_list);
        rl_owner=view.findViewById(R.id.rl_owner);
        mSwipeRefreshView=view.findViewById(R.id.swipe_owner_layout);
        emptyView=view.findViewById(R.id.emptyView);
        errorItem=view.findViewById(R.id.rl_owner_error_item);

        query=view.findViewById(R.id.query);

        clearSearch=view.findViewById(R.id.search_clear);
        ll_right=view.findViewById(R.id.ll_right);
        filterText=view.findViewById(R.id.ib_add_task);

        searchIcon=view.findViewById(R.id.ib_menu_more);

    }
    public ListView mListView;

    public RelativeLayout rl_owner;

    public SwipeRefreshView mSwipeRefreshView;

    public View emptyView;

    public RelativeLayout errorItem;

    public EditText query;

    public ImageButton clearSearch;

    public LinearLayout ll_right;

    public TextView filterText;

    public ImageView searchIcon;


    private List<User> mList;
    private StringAdapter mAdapter;

    private AddrSearchView addrSearchView;

    /**
     * 加载提示Dialog
     */
    public Dialog pd = null;

    private static int curPage = 1;
    private static int totalPage = 0;
    private boolean isHiddenTitle = false;
    //搜索字符串
    private String search_str = "";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_owner_msg, null);
        initFindView(view);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mList = new ArrayList<>();
        mAdapter = new StringAdapter();
        inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);

        mListView.setAdapter(mAdapter);

        // 设置颜色属性的时候一定要注意是引用了资源文件还是直接设置16进制的颜色，因为都是int值容易搞混
        // 设置下拉进度的背景颜色，默认就是白色的
        mSwipeRefreshView.setProgressBackgroundColorSchemeResource(android.R.color.white);
        // 设置下拉进度的主题颜色
        mSwipeRefreshView.setColorSchemeResources(R.color.colorAccent,
                android.R.color.holo_blue_bright, R.color.colorPrimaryDark,
                android.R.color.holo_orange_dark, android.R.color.holo_red_dark, android.R.color.holo_purple);

        mSwipeRefreshView.setItemCount(20);

        // 手动调用,通知系统去测量
        mSwipeRefreshView.measure(0, 0);
        mSwipeRefreshView.setRefreshing(true);

        initEvent();
        initData();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();


    }

    public void setTitleViewHidden(){
        isHiddenTitle = true;
    }

    private void initEvent() {

        rl_owner.setOnTouchListener(new OnDoubleClickListener(new OnDoubleClickListener.DoubleClickCallback() {
            @Override
            public void onDoubleClick() {
                //处理双击事件
                mListView.smoothScrollToPosition(0);
            }
        }));

        if(isHiddenTitle){
            rl_owner.setVisibility(View.GONE);
        }

        String strSearch ="请输入姓名或地址";
        query.setHint(strSearch);
        query.setOnEditorActionListener(new TextView.OnEditorActionListener(){
            @Override
            public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
                if(arg1 == EditorInfo.IME_ACTION_SEARCH)
                {
                    search_str = arg0.getText().toString();
                    if(addrSearchView != null){
                        addrSearchView.clearViewData();
                    }

                    filterText.setTextColor(Color.parseColor("#ffffff"));
                    searchIcon.setImageResource(R.drawable.hk_select_icon);

                    initData();
                }
                return false;
            }

        });

        query.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {

                if (s.length() > 0) {
                    clearSearch.setVisibility(View.VISIBLE);
                } else {
                    clearSearch.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        clearSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                query.getText().clear();
                hideSoftKeyboard();

                search_str = "";
                initData();
            }

        });

        if (getResources().getString(R.string.LI_XIAO_SHUANG).equals(MainActivity.productKey)){
            ll_right.setVisibility(View.GONE);
        }else {
            if (MainActivity.userRole == 1 && TextUtils.isEmpty(MainActivity.village)) {
                ll_right.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (addrSearchView == null) {
                            addrSearchView = new AddrSearchView(getActivity(), OwnerMsgFragment.this, false);
                            addrSearchView.showSearchView();
                            hideSoftKeyboard();

                        } else {
                            if (addrSearchView.isShowing()) {
                                addrSearchView.hideSearchView();
                            } else {
                                addrSearchView.showView();
                                hideSoftKeyboard();
                            }
                        }
                    }

                });
            } else {
                ll_right.setVisibility(View.GONE);
            }
        }

        // 下拉时触发SwipeRefreshLayout的下拉动画，动画完毕之后就会回调这个方法
        mSwipeRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData();
            }
        });

        // 设置下拉加载更多
        mSwipeRefreshView.setOnLoadMoreListener(new SwipeRefreshView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                loadMoreData();
            }
        });
    }

    private void loadMoreData() {

        if(totalPage < curPage){//如果超过页数后
            return;
        }

        curPage = curPage + 1;

        mSwipeRefreshView.setLoading(true);
        ApiService apiService = HKHttpUtils.getApiService();
        Call<BaseResponse<PageWithRes>> call = apiService.getOwnerList(MainActivity.ticket, String.valueOf(MainActivity.userId), String.valueOf(curPage), "20", search_str);
        call.enqueue(new HKResponseResultCallBack<PageWithRes>() {
            @Override
            public void onSuccess(PageWithRes pageWithRes) {
                List<User> users = pageWithRes.getRes();
                if(users.size() != 0){
                    mList.addAll(users);
                }else{
                    Toast.makeText(getActivity(), "没有更多的"+(getResources().getString(R.string.HU_LI_ZHAN).equals(MainActivity.productKey)?"用户":"业主"), Toast.LENGTH_SHORT).show();
                }

//						Toast.makeText(getActivity(), "加载了" + 20 + "条数据", Toast.LENGTH_SHORT).show();
                // 加载完数据设置为不加载状态，将加载进度收起来
                mSwipeRefreshView.setLoading(false);
            }

            @Override
            public void onGetDataFailed(int cd, String msg) {
                Toast.makeText(getActivity(), "请求失败:"+msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailed(Call call, Throwable t) {
                Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
            }
        });
//        OkHttpClient okHttpClient = new OkHttpClient();
//        RequestBody body = new FormBody.Builder()
//                .add("page", String.valueOf(curPage))
//                .add("pagesize", String.valueOf(20))
//                .add("search", search_str)
//                .build();
//
//        Request request = new Request.Builder()
//                .url(BuildConfig.API_URL + "housekeeper/ownerlistsearch")
//                .header("user_id", String.valueOf(MainActivity.userId))
//                .post(body)
//                .build();
//
//        Call call = okHttpClient.newCall(request);
//
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                e.printStackTrace();
//                getActivity().runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
//                    }
//                });
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                final BaseWebResult result = CommonUtils.parseJsonWithGson(response.body().string(), BaseWebResult.class);
//
//                getActivity().runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        List<User> users = result.getData().getRes();
//                        if(users.size() != 0){
//                            mList.addAll(users);
//                        }else{
//                            Toast.makeText(getActivity(), "没有更多的业主", Toast.LENGTH_SHORT).show();
//                        }
//
////						Toast.makeText(getActivity(), "加载了" + 20 + "条数据", Toast.LENGTH_SHORT).show();
//                        // 加载完数据设置为不加载状态，将加载进度收起来
//                        mSwipeRefreshView.setLoading(false);
//                    }
//                });
//
//            }
//        });

    }


    private void initData() {
        curPage = 1;
        ApiService apiService = HKHttpUtils.getApiService();
        Call<BaseResponse<PageWithRes>> call = apiService.getOwnerList(MainActivity.ticket, String.valueOf(MainActivity.userId), String.valueOf(curPage), "20", search_str);
        call.enqueue(new HKResponseResultCallBack<PageWithRes>() {
            @Override
            public void onSuccess(PageWithRes pageWithRes) {
                if (pageWithRes != null){
                    mList.clear();
                    mList.addAll(pageWithRes.getRes());
                    totalPage = pageWithRes.getTotal_page();

                    if(mList.size() == 0){
                        mListView.setVisibility(View.GONE);
                        emptyView.setVisibility(View.VISIBLE);
                    }else{
                        mListView.setVisibility(View.VISIBLE);
                        emptyView.setVisibility(View.GONE);
                        mAdapter.notifyDataSetChanged();
                    }

                    // 加载完数据设置为不刷新状态，将下拉进度收起来
                    if (mSwipeRefreshView.isRefreshing()) {
                        mSwipeRefreshView.setRefreshing(false);
                    }
                }
            }

            @Override
            public void onGetDataFailed(int cd, String msg) {
                Toast.makeText(getActivity(), "请求失败:"+msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailed(Call call, Throwable t) {
                Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
            }
        });
//        OkHttpClient okHttpClient = new OkHttpClient();
//
////		showLoading();
//        System.out.println("initData: " + String.valueOf(MainActivity.userId));
//        curPage = 1;
//
//        RequestBody body = new FormBody.Builder()
//                .add("page", String.valueOf(curPage))
//                .add("pagesize", String.valueOf(20))
//                .add("search", search_str)
//                .build();
//
//        Request request = new Request.Builder()
//                .url(BuildConfig.API_URL + "housekeeper/ownerlistsearch")
//                .header("user_id", String.valueOf(MainActivity.userId))
//                .post(body)
//                .build();
//
//        Call call = okHttpClient.newCall(request);
//
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                e.printStackTrace();
////				hideLoading();
//                getActivity().runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(getActivity(), "请求失败", Toast.LENGTH_SHORT).show();
//                    }
//                });
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//
//                final BaseWebResult result = CommonUtils.parseJsonWithGson(response.body().string(), BaseWebResult.class);
//                getActivity().runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
////						hideLoading();
//
//                        mList.clear();
//                        mList.addAll(result.getData().getRes());
//                        totalPage = result.getData().getTotal_page();
//
//                        if(mList.size() == 0){
//                            mListView.setVisibility(View.GONE);
//                            emptyView.setVisibility(View.VISIBLE);
//                        }else{
//                            mListView.setVisibility(View.VISIBLE);
//                            emptyView.setVisibility(View.GONE);
//                            mAdapter.notifyDataSetChanged();
//                        }
//
//                        // 加载完数据设置为不刷新状态，将下拉进度收起来
//                        if (mSwipeRefreshView.isRefreshing()) {
//                            mSwipeRefreshView.setRefreshing(false);
//                        }
//                    }
//                });
//
//            }
//        });

    }

    void hideSoftKeyboard() {
        if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getActivity().getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public void showLoading() {
        //显示登录提示对话框
        pd = DialogUtils.getLoadingDialog(this.getContext(), "加载中...");
        pd.show();
    }

    public void hideLoading() {
        if(pd != null && pd.isShowing()){
            pd.dismiss();
        }
    }

    @Override
    public void addrSearchRes(String search, String city, String curCityPinyin, String village, String building, String unit, String edit_str) {
        search_str = search;

        query.getText().clear();
        // 如果是清空的话
        if(search.equals("")){
            filterText.setTextColor(Color.parseColor("#ffffff"));
            searchIcon.setImageResource(R.drawable.hk_select_icon);
        }else{
            filterText.setTextColor(Color.parseColor("#FFF16D"));
            searchIcon.setImageResource(R.drawable.hk_select_icon_data);
        }


        initData();
    }

    /**
     * 适配器
     */
    private class StringAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public User getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(getActivity(), R.layout.item_contact, null);
            }

            ImageView icon = (ImageView) convertView.findViewById(R.id.contact_icon);
            TextView name = (TextView) convertView.findViewById(R.id.contact_name);
            TextView addr = (TextView) convertView.findViewById(R.id.contact_addr);

            String wxname = mList.get(position).getWxName();
            String wxhead = mList.get(position).getWxHeader();
            String truename = mList.get(position).getName();

            try {
                if(!CommonUtils.isBlank(truename)){
                    name.setText(truename);
                }else{
                    if(!CommonUtils.isBlank(wxname)) {
                        if(!CommonUtils.isBlank(wxhead) && wxhead.equals("undefined")){
                            name.setText(mList.get(position).getPhone());
                        }else{
                            String decodeStr = URLDecoder.decode(mList.get(position).getWxName(), "utf-8");
                            name.setText(CommonUtils.subStringCN(decodeStr, 30));
                        }
                    }
                }

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                if(!CommonUtils.isBlank(wxname)) {
                    name.setText(wxname);
                }
            }

            addr.setText(mList.get(position).getHomeAddress());

            //加载图片
            Glide.with(getActivity()).load(mList.get(position).getWxHeader())
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE).placeholder(R.drawable.default_agent_avatar).error(R.drawable.default_agent_avatar)
                    .into(icon);

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent = new Intent();

//					HDMessageUser hdUser = new HDMessageUser();
//					String visitorId = mList.get(position).getId()+"_"+mList.get(position).getWxOpenId();

                    intent.setClass(getActivity(), UserMsgListActivity.class);
                    intent.putExtra("id", mList.get(position).getId());
                    intent.putExtra("phone", mList.get(position).getPhone());
                    intent.putExtra("wxHeader", mList.get(position).getWxHeader());
                    intent.putExtra("wxOpenid", mList.get(position).getWxOpenId());
                    intent.putExtra("homeAddress",  mList.get(position).getHomeAddress());
                    intent.putExtra("idcardNumber", mList.get(position).getIdcardNumber());

                    String wxname = mList.get(position).getWxName();
                    try {
                        if(!CommonUtils.isBlank(wxname)) {
                            String decodeStr = URLDecoder.decode(wxname, "utf-8");
                            intent.putExtra("wxname", decodeStr);
                        }else{
                            intent.putExtra("wxname", "");
                        }

                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                        intent.putExtra("wxname", wxname);
                    }

                    String name = mList.get(position).getName();

                    if(!CommonUtils.isBlank(name)){
                        intent.putExtra("name", name);
                    }else{
                        intent.putExtra("name", "");
                    }

                    intent.putExtra("originType", "rest");
                    intent.putExtra("techChannelName", "");
//					intent.putExtra("visitorid", visitorId);
                    intent.putExtra("chatGroupId", 0L);
                    startActivity(intent);


//					Toast.makeText(getActivity(), "点击了第一条", Toast.LENGTH_SHORT).show();
                }
            });

            return convertView;
        }
    }


}

